package com.zzty.servlet;

import com.zzty.common.GunZip;
import com.zzty.common.Log;
import com.zzty.common.PropertyUtil;
import com.zzty.entity.User;
import com.zzty.service.SelfExamService;
import com.zzty.serviceimpl.SelfExamServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.List;

@WebServlet(name="/SelfExamUploadServlet",urlPatterns = "/SelfExamUploadServlet")
public class SelfExamUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // 上传文件存储目录
    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
    GunZip gunZip=new GunZip();
    static PropertyUtil props=new PropertyUtil();


    /**
     * 上传数据及保存文件
     */
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);
        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        // 中文处理
        upload.setHeaderEncoding("UTF-8");
        User user=(User)request.getSession().getAttribute("user");
        String userName=user.getName();
        Calendar cal = Calendar.getInstance();
       userName+=cal.get(Calendar.YEAR)+"_"+(cal.get(Calendar.MONTH)+1)+"_"+cal.get(Calendar.DAY_OF_MONTH);
       System.out.println("userName : "+userName);
       String filePath1 =props.getProp().getProperty("path.zip");
        File storeFile = new File(filePath1);
        if (!storeFile.exists()) {
            storeFile.mkdir();
        }
       String filePath2 = filePath1+"//"+userName +".zip";
        File sFile=new File(filePath2);

        List<FileItem> formItems = null;
        try {
            formItems = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
                if (!item.isFormField()){
                    try {
                        item.write(sFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("filePath2: "+filePath2);
//                    String filePath3=gunZip.uncompress(filePath2,userName);
                    String gunZipPath=props.getProp().getProperty("path.self")+"//"+userName;
                    String filePath3=gunZip.uncompress(filePath2,gunZipPath);
                    updateSelfExamTransaction(request,response,filePath3);
                }
            }
        }
    }

    protected void updateSelfExamTransaction(HttpServletRequest request,
                                             HttpServletResponse response,String filePath) throws ServletException, IOException {
        SelfExamService selfExamService=new SelfExamServiceImpl();
        User user=(User)request.getSession().getAttribute("user");
       Integer userId=user.getId();
        Boolean flag=selfExamService.endSelfExam(userId,filePath);
        response.setContentType("text/html; charset=UTF-8");
        response.sendRedirect("jsp/Smain.jsp");
        PrintWriter out= response.getWriter();
        String json=null;
        ObjectMapper mapper=new ObjectMapper();
        json=mapper.writeValueAsString(flag+"提交成功！");
        out.write(json);
        out.flush();
        out.close();

    }
}
